import logging
from logging import Logger, FileHandler, StreamHandler, Formatter
from typing import Optional

def setup_logger(
    logname: str,
    loglevel: str = 'DEBUG',
    info_log_file: Optional[str] = '', 
    debug_log_file: Optional[str] = '') -> Logger:
    # 配置根日志记录器
    # logging.basicConfig(level=logging.DEBUG)  # 设置最低日志级别
    logging.basicConfig(format='%(name)s-%(asctime)s [%(levelname)s] %(message)s',
                        datefmt="%Y-%m-%d %H:%M:%S", level=logging.DEBUG)

    # 获取根日志记录器
    root_logger: Logger = logging.getLogger()

    # 移除默认的 handler（避免重复输出）
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)

    # 创建 formatter
    formatter: Formatter = logging.Formatter('%(name)s-%(asctime)s [%(levelname)s] %(message)s')

    # 创建 console handler 并设置级别为 INFO
    console_handler: StreamHandler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)
    console_handler.setFormatter(formatter)
    root_logger.addHandler(console_handler)

    # 创建 info file handler 并设置级别为 INFO
    if info_log_file:
        info_file_handler: FileHandler = logging.FileHandler(info_log_file)
        info_file_handler.setLevel(logging.INFO)
        info_file_handler.setFormatter(formatter)
        root_logger.addHandler(info_file_handler)

    # 创建 debug file handler 并设置级别为 DEBUG
    if debug_log_file:
        debug_file_handler: FileHandler = logging.FileHandler(debug_log_file)
        debug_file_handler.setLevel(logging.DEBUG)
        debug_file_handler.setFormatter(formatter)
        root_logger.addHandler(debug_file_handler)

    # 创建自定义 logger
    logger: Logger = logging.getLogger(logname)
    logger.setLevel(logging.DEBUG)  # 设置自定义 logger 的日志级别

    # 将自定义 logger 的日志传播到根日志记录器
    logger.propagate = True
    return logger


